var config=require("./config"),
    ws=require("nodejs-websocket"),
    redis=require("redis"),
    uuid = require('node-uuid')
    url=require("url"),
    queryString=require("queryString"),
    redisClient=redis.createClient(6379,"127.0.0.1");

var connections=[];
//命令
var command={
	Connection:"C"
}

let server = ws.createServer(function (conn) {
   let _url=url.parse(conn.path);
   let _querystring=queryString.parse(_url.query);
   let _uid="";
   //新用户
   if(!_querystring.hasOwnProperty("uid")){
       _uid=uuid.v1();
   }
   else{
       _uid=_querystring.uid;
   }

    var uinfo={
        type:command.Connection,
        uid:_uid
    }
    //保存新用户信息
    connections.push(conn);

    //发送连接信息，保存用户临时ID到redis
    conn.sendText(JSON.stringify(uinfo),function(){
        redisClient.hset("connection","uid",_uid);
        redisClient.expire(uinfo.uid,60*20);
    });
    
    
    conn.on("text", function (str) {
        conn.sendText(str);
    })
    conn.on("close", function (code, reason) {
        console.log("Connection closed")
    })
}).listen(config.port);
console.log("server running...");


module.exports=server;
